'''This file defines UI elements used in the menus in the game.

Defined classes:
- Menu
- Button
- CheckBox
- ColorChooser
- List
- RadioMenu
- RadioButton
- Slider
'''

from os.path import join

from pygame import font, draw, rect, mouse, display, time, event, image
from pygame.locals import *

from locals            import *
from input             import *
from pointer           import *
from extended_graphics import *

ITEM_SPACE          = 10
ITEM_HEIGHT         = 50
SCROLLBAR_WIDTH     = 20
FIXED_BUTTON_HEIGHT = 50

pointers = {}
cursors  = {}
patterns = {}

def return_function():
    pass

class Menu:
    def __init__(self):
        self.items = []
    
    def add_item(self, item):
        self.items.append(item)
    
    def draw(self, surface):
        for item in self.items:
            item.draw(surface)

    def draw_cursors(self, surface):
        global cursors, pointers
        for p in pointers:
            surface.blit(cursors[p], pointers[p].get_pos())

    def create_layout(self, area):
        x = area.x
        y = area.y
        w = area.w
        h = (area.h - (len(self.items)-1)*ITEM_SPACE) / len(self.items)
        for item in self.items:
            item.rect = rect.Rect(x, y, w, h)
            y += ITEM_SPACE + h

    def execute_events(self, events):
        for event in events:
            print event

    def run(self):
        screen = display.get_surface()
        while True:
            event.clear([MOUSEMOTION, MOUSEBUTTONUP, JOYAXISMOTION, KEYDOWN,
                         JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, KEYUP])

            ########################
            if event.get(QUIT):
                break
            ########################

            for item in self.items:
                item.update()

            events = event.get([MOUSEBUTTONDOWN, JOYBUTTONDOWN])

            for p in pointers:
                pointers[p].update(events)
                ppos = pointers[p].get_pos()
                for item in self.items:
                    if item.is_pointed(ppos):
                        item.point()

            clicks = event.get(POINTER_CLICK)
            for click in clicks:
                print click
                mpos = click.pos
                for item in self.items:
                    if item.is_pointed(mpos):
                        f = item.function
                        if f:
                            return f

            screen.fill(BLACK)
            self.draw(screen)
            self.draw_cursors(screen)
            display.flip()
            time.wait(10)
            
        
class Button:
    def __init__(self, text, function=return_function, rect=None):
        self.rect      = rect
        self.text      = text
        self.function  = function
        self.highlight = False
        self.disabled  = False
    
    def draw_text(self, surface):
        global std_font
        if self.disabled:
            text = std_font.render(self.text, False, BLACK)
        else:
            text = std_font.render(self.text, False, WHITE)
        text_rect = text.get_rect(center=(self.rect.centerx, self.rect.centery))
        surface.blit(text, text_rect)
        
    def draw(self, surface):
        if self.disabled:
            draw.rect(surface, GRAY, self.rect)
            if self.highlight:
                draw.rect(surface, WHITE, self.rect, 1)
            self.draw_text(surface)
            return
        if self.highlight:
            pattern_fill(patterns['yellow'], surface, self.rect)
            draw.rect(surface, WHITE, self.rect, 1)
        else:
            pattern_fill(patterns['blue'], surface, self.rect)
        self.draw_text(surface)
    
    def is_pointed(self, pos):
        return self.rect.collidepoint(pos)

    def point(self):
        self.highlight = True

    def press(self):
        if self.disabled:
            #Play Fail sound
            return None
        else:
            #Play Button_press sound
            return self.function

    def update(self):
        self.highlight = False

class ScrollBar:
    def __init__(self, area, data_list):
        self.area         = area
        self.data_list    = data_list
        self.bar          = rect.Rect(area.x, area.y, SCROLLBAR_WIDTH, 1)

    def draw(self, surface):
        #Draw whole bar
        draw.rect(surface, WHITE, self.rect, 1)

        #Get bar height
        total_height = len(self.data_list) * ITEM_HEIGHT
        if self.area.h >= total_height:
            return
        self.bar.h = self.area.h*self.area.h / total_height

        #Draw bar in appropriate position
        draw.rect(surface, YELLOW, self.bar)

    def get_position(self):
        '''Returns the position of the top pixel in the list which should be
        displayed.'''
        total_height = len(self.data_list) * ITEM_HEIGHT
        y = self.bar.y - self.area.y
        yrel = y*self.area.h/total_height
        return yrel
        
class ListMenu(Menu):
    def __init__(self):
        Menu.init(self)
        self.list_items = []
        self.position   = 0

    def add_list_item(self, item):
        self.list_items.append(item)

    def draw_scrollbar(self):
        pass

    def create_layout(self, area):
        self.rect = area
        x = area.x
        y = area.y
        w = area.w - SCROLLBAR_WIDTH
        h = (area.h - (len(self.items)-1)*ITEM_SPACE) / len(self.items)
        for item in self.items:
            item.rect = rect.Rect(x, y, w, h)
            y += ITEM_SPACE + h

    

    #add item
    #ok
    #cancel

class CheckBox:
    pass

class ColorChooser:
    pass


class ListItem:
    pass

class RadioMenu:
    pass

class RadioButton:
    pass

class Slider:
    pass

def ui_init():
    '''Initializes this library. Must be called after input_init. Initializes
    mouse and joystick pointer devices.'''
    global std_font, cursors, pointers

    std_font = font.Font(join("data", "fonts", "DejaVuSerif.ttf"), 12)

    #Define mouse pointer and cursor
    pointers['mouse'] = MousePointer(0)
    cursors['mouse']  = image.load(join("data", "images", "cursor_mouse.png"))

    #Define joystick pointers and cursor
    for j in joysticks:
        p = JoystickPointer("joystick"+str(j.get_id()), j)
        pointers[p.name] = p
        cursors[p.name]  = image.load(join("data", "images", "cursor_joystick.png"))

    patterns['blue']   = image.load(join("data", "images", "blue_pattern.png"))
    patterns['gray']   = image.load(join("data", "images", "gray_pattern.png"))
    patterns['yellow'] = image.load(join("data", "images", "yellow_pattern.png"))

